﻿<?php

App::uses('PrivadoController', 'Controller');
App::uses('Folder', 'Utility');
App::uses('Encabezado', 'Model/Banorte/Altas');
App::uses('Detalle', 'Model/Banorte/Altas');
App::import('Vendor', 'PHPExcel/IOFactory');

class AltController extends PrivadoController
{

    public function __construct($request = null, $response = null) {
        parent::__construct($request, $response);
        $this->layout = 'privado';
    }

    public function index() {
        $this->request->onlyAllow('GET');
        $dt = new DateTime();
        $this->set('year', $dt->format('Y'));
        $this->set('title', 'Generación de archivos .ALT');
        $this->set('description', '');
    }

    public function restricciones() {
        $this->request->onlyAllow('POST');
        $filesOK = array_filter($_FILES, function($file) {
            if ($file['error'] == UPLOAD_ERR_OK) {
                return $file;
            }
        });
        if (count($filesOK) == 0) {
            $this->redirect('index');
        } else {
            $nameFile = $this->moveUpload($filesOK);
            $this->set('nameFile', $nameFile);
            $this->set('title', 'Generación de archivos .ALT');
            $this->set('description', 'Confirmación');
        }
    }

    public function procesa() {
        $this->request->onlyAllow('GET');
        set_time_limit(36000);
        $altas = $_SESSION['altas'];
        if ($altas !== null) {
            $ubicacion = $altas->files[0];
            $inputFileType = PHPExcel_IOFactory::identify($ubicacion);
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($ubicacion);
            $worksheet = $objPHPExcel->getActiveSheet();
            $detalles = array();
            for ($i = 6; true; $i++) {
                $rfc = $worksheet->getCellByColumnAndRow(2, $i)->getValue();
                $nombre = $worksheet->getCellByColumnAndRow(3, $i)->getValue();
                $cuenta = $worksheet->getCellByColumnAndRow(4, $i)->getValue();
                $identificacion = $worksheet->getCellByColumnAndRow(5, $i)->getValue();
                $montoMaximo = $worksheet->getCellByColumnAndRow(6, $i)->getValue();
                if ($rfc == '') {
                    break;
                }
                $detalle = new Detalle($rfc, $montoMaximo, $nombre, $cuenta, $identificacion);
                $strDetalle = $detalle->getString();
                $detalles[] = $strDetalle;
            }
            $dt = new DateTime();
            $encabezado = new Encabezado(32155, $dt->format('Ymd'), count($detalles));
            $strEncabezado = $encabezado->getString();
            $strDetalles = implode("\r\n", $detalles);
            $pathParts = pathinfo($ubicacion);
            $name = $pathParts['dirname'] . DS . 'CI3215501.alt';
            $fileAlt = fopen($name, "w+");
            fwrite($fileAlt, $strEncabezado);
	    fwrite($fileAlt, "\r\n");
            fwrite($fileAlt, $strDetalles);
            fclose($fileAlt);
        }
        $this->set('title', 'Generación de archivos .ALT');
        $this->set('description', 'Resultado y descarga');
    }

    private function moveUpload($files) {
        $recuperaciones = new stdClass();
        $recuperaciones->files = array();
        foreach ($files as $file => $data) {
            $tmp_name = $data["tmp_name"];
            $dt = new DateTime();
            $date = $dt->format('Ymd');
            $hour = $dt->format('His');
            $path = WWW_ROOT . 'files' . DS . 'Altas' . DS . $date . DS . $hour;
            new Folder($path, true, 0755);
            $name = $path . DS . $data["name"];
            move_uploaded_file($tmp_name, $name);
            $recuperaciones->files[] = $name;
        }
        $_SESSION['altas'] = $recuperaciones;
        return count($recuperaciones->files) > 0 ? basename($recuperaciones->files[0]) : '';
    }

    public function download() {
        $this->request->onlyAllow('GET');
        $altas = $_SESSION['altas'];
        $path = $altas->files[0];
        $parts = explode(DS, $path);
        $partsReverse = array_reverse($parts);
        $relativeParts = array_slice($partsReverse, 1, 4);
        $reverseRelativeParts = array_reverse($relativeParts);
        $reverseRelativeParts[] = 'CI3215501.alt';
        $pathDownload = implode(DS, $reverseRelativeParts);
        $options = array(
            'download' => true,
            'name' => 'CI3215501.alt',
        );
        $this->response->file($pathDownload, $options);
        return $this->response;
    }

    public function downloadLayout() {
        $options = array(
            'download' => true,
            'name' => 'layout altas.xlsx',
        );
        $this->response->file('files' . DS . 'Altas' . DS . 'layout' . DS . 'layout altas.xlsx', $options);
        return $this->response;
    }

    public function downloadHistory($dir1, $dir2) {
        $options = array(
            'download' => true,
            'name' => 'CI3215501-' . $dir2 . '-' . $dir1 . '.alt',
        );
        $this->response->file('files' . DS . 'Altas' . DS . $dir2 . DS . $dir1 . DS . 'CI3215501.alt', $options);
        return $this->response;
    }

    public function scan() {
        $dir = new Folder('files' . DS . 'Altas');
        $files = $dir->findRecursive('CI3215501.alt');
        $f = array();
        foreach ($files as $filePath) {
            $file = new File($filePath);
            $path = $file->Folder->path;
            $parts = explode(DS, $path);
            $partsReverse = array_reverse($parts);
            $f[] = array(
                $partsReverse[0],
                $partsReverse[1],
                date("F d Y H:i:s.", filemtime($filePath)),
            );
        }
        $this->set('files', $f);
        $this->set('title', 'Generación de archivos .ALT');
        $this->set('description', 'Archivos generados');
    }

}
